<template>
  <div class="article-container">
    <el-card class="box-card">
      <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-tiptap
            v-model="form.content"
            :extensions="extensions"
            lang="zh"
            placeholder="你想输入点什么 …"
            width="100%"
            :height="600"
          />
        </el-form-item>
        <el-form-item label="封面" prop="cover_type">
          <el-radio-group v-model="form.cover_type">
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="10">自动</el-radio>
          </el-radio-group>
          <!-- 传统父子传值 -->
            <template v-if="form.cover_type > 0 && form.cover_type <=3">
           <upload-cover v-for="(cover,index) in form.cover_type" :key="cover" class="upload-cover" @yunImage="yunImage(index,$event)" :cover-image="images[index]"/>
          </template>
        </el-form-item>
        <el-form-item label="频道" prop="category_id">
          <el-select v-model="form.category_id" placeholder="请选择频道">
            <el-option
              v-for="item in articleCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add">{{ title }}</el-button>
          <el-button @click="cun">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import UploadCover from '@/views/article/components/UploadCover'
import { uploadImgMax } from "@/api/upload";
import {
  ElementTiptap,
  // 需要的 extensions
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  Link,
  Image,
  Iframe,
  CodeBlock,
  Blockquote,
  // ListItem,
  // BulletList,
  // OrderedList,
  TodoItem,
  TodoList,
  TextAlign,
  Indent,
  LineHeight,
  HorizontalRule,
  HardBreak,
  TrailingNode,
  History,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  FormatClear,
  TextColor,
  TextHighlight,
  Preview,
  Print,
  Fullscreen,
  SelectAll,
  FontType,
  FontSize,
  CodeView,
} from "element-tiptap";
// import element-tiptap 样式
import "element-tiptap/lib/index.css";
import { addArticle, editArticle, getArticleId } from "@/api/article";
import {  getArticleCategoryList} from "@/api/articleCategory";
import { mapGetters } from "vuex";
export default {
  name: "Published",
  components: {
    "el-tiptap": ElementTiptap,
    UploadCover
  },
  data() {
    const checkContent = (rule, value, callback) => {
        if (value === '<p></p>') {
          return callback(new Error('请输入文章内容1'));
        }else {
          callback()
        }
    }
    return {
      // 它们将会按照你声明的顺序被添加到菜单栏和气泡菜单中
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline({ bubble: true, menubar: false }), // 在气泡菜单而不在菜单栏中渲染菜单按钮

        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new TodoItem(),
        new TodoList(),
        new TextAlign(),
        new Indent(),
        new Blockquote(), // 引用
        new LineHeight(),
        new FontType(),
        new TextColor(),
        new TextHighlight(),
        new FontSize(),
        new Link(),
        new Image({
          // 默认会把图片生成base64字符串和内容存储在一起不太好
          // 自定义图片上传
          // 返回一个promise<url>
          uploadRequest(file) {
            let fd = new FormData();
            fd.append("image", file);
            return uploadImgMax(fd).then((res) => {
              return res.image;
            });
          },
        }),
        new Iframe(),
        new CodeBlock(),
        // new ListItem(),
        // new BulletList(),
        // new OrderedList(),
        new HorizontalRule(),
        new HardBreak(),
        new TrailingNode(),
        new Table(),
        new TableHeader(),
        new TableCell(),
        new TableRow(),
        new Italic(),
        new Strike(),
        new FormatClear(),
        new SelectAll(),
        new Print(),
        new Preview(),
        new CodeView(),
        new Fullscreen(),
        new History(),
      ],
      form: {
        title: "",
        content: "",
        category_id: "",
        cover_type: 1,
        status: 0,
        cover_img:'',
      },
      images:[],// 这个数组存的是3张图片的数据 目前没用上,
      formRules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { max: 100, message: "长度最大 100 个字符", trigger: "blur" },
        ],
        content: [
         { validator: checkContent, trigger: 'blur' },
         { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
        cover_type: [
          { required: true, message: "请选择封面类型", trigger: "change" },
        ],
        category_id: [
          { required: true, message: "请选择频道", trigger: "change" },
        ],
      },
      title: this.$route.query.id ? "修改文章" : "发布文章",
      articleCategoryList: [], // 频道数据
    };
  },
  created() {
    this.getArticleCategoryList();
    if (this.$route.query.id) {
      this.getArticleId(this.$route.query.id);
    }
  },
  computed: {
    ...mapGetters(["user_name", "userId"]),
  },
  methods: {
    // 接收子组件传递过来的 yunImage  index是父组件传过来的
    yunImage(index,yunImage){
        this.images[index] = yunImage
        this.form.cover_img = this.images[0]
    },
    // 文章频道数据
    async getArticleCategoryList() {
      const { list } = await getArticleCategoryList();
      this.articleCategoryList = list;
    },
    // 根据文章id获取文章信息
    async getArticleId(id) {
      this.form = await getArticleId(id);
       this.images[0] = this.form.cover_img
    },
    // 根据id修改文章信息
    async editArticle() {
      await editArticle(this.$route.query.id, this.form);
      this.$message.success("修改成功");
      setTimeout(() => {
        this.$router.push("/article/list");
      }, 1000);
    },
    // 发布文章
    addArticle() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await addArticle({
            ...this.form,
            user_id: this.userId,
            aut_name: this.user_name,
          });
          this.$message.success(
            res.status === 1 ? "发布文章成功" : "文章已存入草稿"
          );
          setTimeout(() => {
            this.$router.push("/article/list");
          }, 1000);
        } else {
          return false;
        }
      });
    },
    // 点击了存入草稿
    cun() {
      this.form.status = 0;
      if (this.$route.query.id) {
        this.editArticle();
      } else {
        this.addArticle();
      }
    },
    // 点击了发布文章
    add() {
      this.form.status = 1;
      if (this.$route.query.id) {
        this.editArticle();
      } else {
        this.addArticle();
      }
    },
  },
};
</script>

<style lang="scss">
.article-container {
  // height: 100vh;
}
.upload-cover{
  // width: 100%;
  // width: 160px;
  // display:flex;
  // float:left;
}
.box-card {
  // height: 100%;
  margin: 20px;
}
</style>
